package com.lagou.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.lagou.base.BaseServlet;
import com.lagou.base.Constants;
import com.lagou.pojo.Course;
import com.lagou.service.CourseService;
import com.lagou.service.impl.CourseServiceImpl;
import com.lagou.utils.DateUtils;
import com.lagou.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/course")
public class CourseServlet extends BaseServlet {

    /**
     * 查询课程列表
     * @param request
     * @param response
     */
    public void findCourseList(HttpServletRequest request, HttpServletResponse response) {
        try {
            CourseService courseService = new CourseServiceImpl();
            List<Course> courseList = courseService.findCourseList();

            //SimplePropertyPreFilter 指定要转换的JSON字段
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Course.class,
                    "id","course_name","price","sort_num","status");

            String result = JSON.toJSONString(courseList, filter);

            response.getWriter().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据课程名称和状态查询课程列表
     * @param request
     * @param response
     */
    public void findByCourseNameAndStatus(HttpServletRequest request, HttpServletResponse response) {

        try {
            CourseService courseService = new CourseServiceImpl();

            String courseName = request.getParameter("courseName");

            String status = request.getParameter("status");

            List<Course> courseList = courseService.findByCourseNameAndStatus(courseName, status);

            //SimplePropertyPreFilter 指定要转换的JSON字段
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Course.class,
                    "id","course_name","price","sort_num","status");

            String result = JSON.toJSONString(courseList, filter);

            response.getWriter().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存课程营销信息
     *      收集表单数据,封装到course对象中,将图片上传到tomcat服务器中
     * @param request
     * @param response
     */
    public void saveCourseSalesInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            CourseService courseService = new CourseServiceImpl();

            Course course = new Course();

            Map<String, Object> map = new HashMap<>();

            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload fileUpload = new ServletFileUpload(factory);

            List<FileItem> list = fileUpload.parseRequest(request);

            for (FileItem item : list) {
                boolean formField = item.isFormField();

                // 是普通表单项
                if(formField) {
                    String fieldName = item.getFieldName();

                    String value = item.getString("UTF-8");

                    map.put(fieldName, value);
                } else { // 是文件上传项
                    // 获取上传文件名称
                    String fileName = item.getName();
                    // 重命名
                    String newFileName = UUIDUtils.getUUID() + "_" + fileName;
                    // 获取输入流
                    InputStream inputStream = item.getInputStream();
                    // 获取webapps路径
                    String realPath = this.getServletContext().getRealPath("/");
                    String webapps = realPath.substring(0, realPath.indexOf("lagou_edu_home"));
                    // 输出流文件
                    FileOutputStream fileOutputStream = new FileOutputStream(webapps + "/upload/" + newFileName);

                    IOUtils.copy(inputStream, fileOutputStream);
                    fileOutputStream.close();
                    inputStream.close();

                    // 保存文件路径
                    map.put("course_img_url", Constants.LOCAL_URL + "/upload/" + newFileName);
                }

            }

            BeanUtils.populate(course, map);
            String result = "";

            // 判断是新增还是修改
            String id = (String) map.get("id");
            String srcDate = DateUtils.getDateFormart();
            // 修改操作
            if(id != null && !"".equals(id)) {
                course.setUpdate_time(srcDate);
                System.out.println("修改操作");
                result = courseService.updateCourseSalesInfo(course);
            } else { // 新增操作
                course.setCreate_time(srcDate);
                course.setUpdate_time(srcDate);
                course.setStatus(1);
                System.out.println("新增操作");
                result = courseService.saveCourseSalesInfo(course);
            }

            response.getWriter().print(result);
        } catch (FileUploadException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据课程id查询课程信息
     * @param request
     * @param response
     */
    public void findCourseById(HttpServletRequest request, HttpServletResponse response) {
        try {
            CourseService courseService = new CourseServiceImpl();

            String id = request.getParameter("id");

            Course course = courseService.findCourseById(Integer.parseInt(id));

            String result = JSON.toJSONString(course);

            response.getWriter().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改课程状态
     * @param request
     * @param response
     */
    public void updateCourseStatus(HttpServletRequest request, HttpServletResponse response) {
        try {
            CourseServiceImpl courseService = new CourseServiceImpl();

            String id = request.getParameter("id");

            // 根据id查询课程信息
            Course course = courseService.findCourseById(Integer.parseInt(id));

            // 获取课程状态
            int status = course.getStatus();

            if(status == 0) {
                course.setStatus(1);
            } else {
                course.setStatus(0);
            }
            course.setUpdate_time(DateUtils.getDateFormart());

            Map<String, Integer> map = courseService.updateCourseStatus(course);

            String result = JSON.toJSONString(map);

            response.getWriter().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
